package com.lengxf.redis.redisTest.listener;

import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.Properties;

/**
 * redis 监听事件
 * 参考 spring自带实现
 * {@link org.springframework.data.redis.listener.KeyspaceEventMessageListener}
 *
 * @Author Lengxf
 */
public class RedisKeyChangeListener implements MessageListener {
    private static final Topic TOPIC_ALL_KEYEVENTS = new PatternTopic("__keyevent@*"); //表示只监听所有的key
    private static final Topic TOPIC_KEYEVENTS_SET = new PatternTopic("__keyevent@*__:set"); //表示只监听所有的key
    private static final Topic TOPIC_KEYNAMESPACE_NAME = new PatternTopic("__keyspace@0__:myKey"); // 不生效
    // 监控
    //private static final Topic TOPIC_KEYEVENTS_NAME_SET_USELESS = new PatternTopic("__keyevent@0__:set myKey");
    private static final String keyspaceNotificationsConfigParameter = "KEA";

    public RedisKeyChangeListener(RedisMessageListenerContainer listenerContainer) {
        initAndSetRedisConfig(listenerContainer);
    }

    @SuppressWarnings("all")
    public void initAndSetRedisConfig(RedisMessageListenerContainer listenerContainer) {
        if (StringUtils.hasText(keyspaceNotificationsConfigParameter)) {
            try (RedisConnection connection = Objects.requireNonNull(listenerContainer.getConnectionFactory()).getConnection()) {
                Properties config = connection.getConfig("notify-keyspace-events");
                if (!StringUtils.hasText(config.getProperty("notify-keyspace-events"))) {
                    connection.setConfig("notify-keyspace-events", keyspaceNotificationsConfigParameter);
                }
            }
        }
        listenerContainer.addMessageListener(this, TOPIC_KEYNAMESPACE_NAME);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        System.out.println("key发生变化===》" + message);
        byte[] body = message.getBody();
        String string = new String(body, StandardCharsets.UTF_8);
        System.out.println(string);
    }
}
